interface HookOptions {
  sync?: boolean
}

type LocaleType = 'zh-CN' | 'en'

type Field = { [key in LocaleType]: string | undefined }

export default function useLangField(opt?: HookOptions) {
  const field = ref<Field>({
    'zh-CN': undefined,
    'en': undefined,
  })

  function parse(jsonStr: string) {
    try {
      const json = JSON.parse(jsonStr) as Field
      if (!opt?.sync) {
        return json
      }
      for (const key in field.value) {
        if (key in json) {
          field.value[key as LocaleType] = json[key as LocaleType]
        }
      }
    } catch (error) {
      console.error('多语言字段解析失败', error)
    }
  }

  function stringify() {
    return JSON.stringify(field.value)
  }

  return {
    field,
    parse,
    stringify,
  }
}
